<?php

namespace common\models\user;

use Yii;
use common\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%user_signin}}".
 *
 * @property int $id
 * @property int $user_id 用户UID
 * @property int $amount 总签到数
 * @property int $serial 最近连续签到数
 * @property int $max_serial 最长连续签到数
 * @property int $repairs 历史补签数
 * @property int $last_time 最后签到时间
 * @property string $recent 最近两月签到历史
 * @property int $current_id 当前周期日志ID
 * @property int $created_at 首次签到时间
 * @property int $updated_at
 */
class UserSignin extends \common\db\ActiveRecord {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user_signin}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'amount', 'serial', 'max_serial', 'repairs', 'last_time', 'recent', 'current_id', 'created_at', 'updated_at'], 'integer'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => '用户UID',
            'amount' => '总签到数',
            'serial' => '最近连续签到数',
            'max_serial' => '最长连续签到数',
            'repairs' => '历史补签数',
            'last_time' => '最后签到时间',
            'recent' => '最近两月签到历史',
            'current_id' => '当前周期日志ID',
            'created_at' => '首次签到时间',
            'updated_at' => 'Updated At',
        ];
    }

    public function getPeriods() {
        return \common\logics\base\SigninCalendarLogic::periodDays($this->last_time, $this->recent);
    }

    public function getMonth() {
        return array_sum(str_split(decbin($this->recent)));
    }

    public function getCurrentLog() {
        return $this->hasOne(UserSigninHistory::className(), ['id' => 'current_id']);
    }

    public function getRecentSigned() {
        $periods = $this->periods;

        $signeds = ArrayHelper::getColumn($periods, function ($element) {
            if ($element['signed']) {
                return $element['date'];
            }
        });
        return array_filter($signeds);
    }

    public function getToday() {
        $duration = Yii::$app->formatter->asDateDiff($this->last_time);
        if (!$duration) {
            return [
                'status' => true,
                'date' => date('Y-m-d', $this->last_time),
                'text' => '今日已签',
                'desc' => '+5经验',
            ];
        }
        return [
            'status' => false,
            'date' => date('Y-m-d', $this->last_time),
            'text' => '点击签到',
            'desc' => '加经验',
        ];
    }

}
